<template>
	<view class="container">
		<scroll-view scroll-y="true" class="cenScr p_rlt">
			<view class="padding-lr-sm padding-tb-sm">
				<empty positions="absolute" :empty="list.length<=0"
					:imgUrl="'https://cdn-static.yekjx.com/'+'food/empty/images/empty_ico01.png'" content="还没有添加地址哦！">
				</empty>
				<view v-for="(item,index) in list" :key="index" @click="tapSelecItem(item,index)"
					:class="{ 'listHover': scrClass == index }"
					class="srcItem margin-bottom-sm padding-top-xl padding-left-lg padding-bottom lh_xs">
					<view class="flex align-center padding-right-lg text-lg">
						<view class="flex-sub flex align-center text-cut">
							<view class="d_ib text-df lbyuan text-center text-bold" v-if="item.addre_type"
								:class="item.addre_type=='1136' ? 'ji' : 'gs'">
								{{ item.addre_type === '1136' ? '家' : (item.addre_type === '1137' ? '公司' : '学校') }}
							</view>
							<view v-if="item.vname" class="padding-left-xs padding-right">
								{{item.vname||''}}
							</view>
							<view>
								{{item.vphone||''}}
							</view>
						</view>
						<text class="text-c9 text-xl"
							:class="[scrClass==index?'textact cuIcon-roundcheckfill':'cuIcon-round text-c9']"></text>
					</view>
					<view class="text-c9 text-df padding-lr-xs padding-top text-cut">
						{{ item.vprovince }}&ensp;{{ item.vcity }}&ensp;{{ item.vcounty }}&ensp;{{ item.vaddre_detail }}
						<!-- {{(item.province||'') + (item.city||'') + (item.area||'') + (item.address_info||'') }} -->
					</view>
					<view class="text-c9 padding-right text-xl actions">
						<view class="flex center padding-tb-xs" @click.stop="defaultaddress(item,index)">
							<view class="defSwitch"
								:style="{backgroundColor:item.vdefault=='5'?'#E5F7E9':'rgba(203, 201, 201, 0.30);'}">
								<view :class="item.vdefault=='5'?'acSwitch':'unact'"></view>
							</view>
							<view v-if="item.vdefault!='5'" class="swi_text">
								设为默认地址
							</view>
						</view>
						<view>
							<view class="d_ib text-acenter itm_btn padding-tb-sm" @click.stop="editAddress(item,index)">
								<text class="cuIcon-edit"></text>
							</view>
							<view class="d_ib text-acenter itm_btn margin-left-xs padding-tb-sm"
								@click.stop="tapDelItem(item.naddress_id,index)">
								<text class="cuIcon-delete"></text>
							</view>
						</view>
					</view>
				</view>
				<!-- 超出配送范围 :class="{ 'listHover': scrClass == index }"-->
				<view v-for="(item,index) in overAdresLisst" :key="index" @click="tapSelecItem(item,index)"
					class="srcItem gry margin-bottom-sm padding-top-xl padding-left-lg padding-bottom lh_xs">
					<view class="flex align-center padding-right-lg text-lg">
						<view class="flex-sub flex align-center text-cut">
							<view class="d_ib text-df lbyuan text-center text-bold" v-if="item.addre_type"
								:class="item.addre_type=='1136' ? 'ji' : 'gs'">
								{{ item.addre_type === '1136' ? '家' : (item.addre_type === '1137' ? '公司' : '学校') }}
							</view>
							<view v-if="item.vname" class="padding-left-xs padding-right">
								{{item.vname||''}}
							</view>
							<view>
								{{item.vphone||''}}
							</view>
						</view>
						<text class="text-c9 text-xl ovbx"
							:class="[scrClass==index?'textact cuIcon-roundcheckfill':'cuIcon-round text-c9']"></text>
					</view>
					<view class="text-c9 text-df padding-lr-xs padding-top text-cut ovbx">
						{{ item.vprovince }}&ensp;{{ item.vcity }}&ensp;{{ item.vcounty }}&ensp;{{ item.vaddre_detail }}
						<!-- {{(item.province||'') + (item.city||'') + (item.area||'') + (item.address_info||'') }} -->
					</view>
					<view class="text-c9 padding-right text-xl actions ovbx">
						<view class="flex center padding-tb-xs" @click.stop="defaultaddress(item,index)">
							<view class="defSwitch"
								:style="{backgroundColor:item.vdefault=='5'?'#E5F7E9':'rgba(203, 201, 201, 0.30);'}">
								<view :class="item.vdefault=='5'?'acSwitch':'unact'"></view>
							</view>
							<view v-if="item.vdefault!='5'" class="swi_text ovbx">
								设为默认地址
							</view>
						</view>
						<view>
							<view class="d_ib text-acenter itm_btn padding-tb-sm" @click.stop="editAddress(item,index)">
								<text class="cuIcon-edit"></text>
							</view>
							<view class="d_ib text-acenter itm_btn margin-left-xs padding-tb-sm"
								@click.stop="tapDelItem(item.naddress_id,index)">
								<text class="cuIcon-delete"></text>
							</view>
						</view>
					</view>
				</view>
				
			</view>

		</scroll-view>
		<view class="botSec text-lg">
			<view class="margin-top-lg margin-bottom-sm full_btn">
				<view class="mbtn" @click="mnavTo('/pages/others/addNewAddress/addNewAddress')">新建送餐地址</view>
			</view>
			<!-- <view class="text-center">
				<view class="d_ib padding-top-sm padding-bottom-xl padding-lr-xl">
					获取微信地址
				</view>

			</view> -->
		</view>
	</view>
</template>

<script lang="ts" setup>
	import { ref } from "vue";
	import { onShow, onLoad } from '@dcloudio/uni-app';
	import { mnavTo, showLoading, hideLoading, } from '@/utils/helper';
	import { getAddressList, getsaveAddressList, getdeleteAddress } from '@/api/vmeitime-http/index.js'
	import { useUserStore } from '@/stores/commonStore';
	import mapi from '@/utils/mapi';
	import global from '@/utils/global';
	const isLogin = ref(false)  //是否登录
	const userStore = useUserStore();

	const list = ref([])  //地址列表
	const adressInfo = ref('')
	const scrClass = ref(null) //选中列表
	const source = ref()
	const flagStatue = ref(null)
	const sourceFlag = ref<any>(false)
	// import mapi from "@/utils/mapi";
	onLoad((option) => {
		console.log('option-----', option.source);
		if (option.source) {
			source.value = option.source
			sourceFlag.value = true
			adressInfo.value = option.adressInfo
		} else {
			source.value = ''
		}
	})
	onShow(() => {
		// this.$myGlobalMethod()
		// console.log(getApp().$vm.$myGlobalMethod,'this');
		// const tem2 = getCurrentInstance().appContext.config.globalProperties.$myGlobalMethod
		// isLogin.value = uni.getStorageSync(global.IS_LOGIN) || false;
		// console.log('是否登录--------------------------------------------------', isLogin.value)
		// if (!isLogin.value) {
		// 	mnavTo(`/pages/login/login`)
		// }
		getApp().$vm.$myGlobalMethod()
		console.log('gloab', getApp().$vm.timeStr);
		getAddressListData()
	})
	
	// 选中
	const tapSelecItem = (item : any, index : any) => {
		if (source.value) {
			if(item.exceedDistanceRange!='5'){
				uni.showModal({
					title: '提示',
					content: '该地址不在配送范围哦',
					showCancel: false,
					confirmText: '知道了'
				})
				return
			}
			scrClass.value = index;
			item.adrs = (item.vprovince || '') + (item.vcity || '') + (item.vcounty || '') + (item.vaddre_detail || '');
			item.source = source.value;
			userStore.setSelectAdress(item);
			// source.value==='menu'&&
			userStore.setChangeAdress(true);
			source.value=='manyMeals'&&uni.setStorageSync('mealsAdresTips',true);//  userStore.setMealsAdress(item);
			console.log(item)
			uni.navigateBack()
		}
	}
	//编辑
	const editAddress = (item : AnyObject, index : any) => {
		scrClass.value = index
		flagStatue.value = true
		sourceFlag.value = false
		// userStore.setSelectAdress(item)
		console.log('选中,------------------------------------------------', item)
		// mnavTo(`/pages/others/addNewAddress/addNewAddress?flagStatue=${flagStatue.value}&&${item}`);
		mnavTo('/pages/others/addNewAddress/addNewAddress?flagStatue=' + flagStatue.value + '&data=' + JSON.stringify(item));
	}
	//删除
	const tapDelItem = async (id : any, index : any) => {
		console.log('4654654654d5s4a65d4asd', id);
		scrClass.value = index
		sourceFlag.value = false
		uni.showModal({
			title: '提示',
			content: '确定删除此条地址信息吗？',
			success: function (e) {
				if (e.confirm) {
					deleAddress(id)
				}
			}
		})

	}
	const deleAddress = async (id : any) => {
		try {
			let res = await getdeleteAddress({
				addressId: id
			})
			console.log('删除地址返回', res)
			if (res.result) {
				//删除缓存
				let cachId = userStore.curSelecAdress.naddress_id || '';
				if (cachId && cachId == id) {
					userStore.setSelectAdress({})
					userStore.setChangeAdress(true);
				}
				//重新获取收获地址
				getAddressListData()
			} else {
				hideLoading();
				mapi.msg(res.shortMessage || '网络繁忙，请稍后再试!');
			}
		} catch (e) {
			hideLoading();
			mapi.msg('删除地址失败!');
		}
	}
	const overAdresLisst = ref<any>([]);
	//获取地址列表
	const getAddressListData = async () => {
		// console.log('我是获取地址列表的接口')
		showLoading();
		try {
			let data:any = {channelNo:'1114'};
			source.value?data.scene = 1:'';
			let res = await getAddressList(data)
			hideLoading();
			if (res) {
				let clist:any=[],nlist:any=[];
				res.forEach((item : any) => {
					item.vaddre_detail = item.vaddre_detail.replace(/&middot;/g, '·');
					if(source.value){
						item.exceedDistanceRange == '5'?clist.push(item):nlist.push(item)
					}
				})
				overAdresLisst.value = source.value?nlist:[];
				list.value = source.value?clist:res || [];
				if (source.value && sourceFlag.value) {
					const indexNum = list.value.findIndex((item : any) => {
						return item.naddress_id == adressInfo.value
					})
					scrClass.value = indexNum
				}
				console.log('获取地址列表----------------------------------------------------------------------', res)
			}
		} catch (e) {
			hideLoading();
			// mapi.msg('获取门店失败!');
		}
	}

	//设为默认地址
	const defaultaddress = async (item : any, index : any) => {
		// if(!source.value||(source.value&&item.exceedDistanceRange=='5')){
			
		// }
		
		scrClass.value = index
		flagStatue.value = true
		sourceFlag.value = false
		if (item.vdefault == 5) return
		collection(item)
	}

	//收藏
	const collection = async (item : any) => {
		try {
			showLoading()
			console.log('收藏收藏收藏')
			// const cleanedVaddreDetail = item.vaddre_detail.replace(/[^\w\s]/gi, '');
			let res = await getsaveAddressList({
				vphone: item.vphone,   //手机号码
				nmember_id: 152998,  //
				vcounty: item.vcountyCode,
				vname: item.vname,  //联系人
				// labelname:addressData.value.labelname, //  分类
				vaddre_detail: item.vaddre_detail, //详细地址
				// address:addressData.value.address,
				vdefault: '5',//5
				naddress_id: item.naddress_id
			})
			console.log(res)
			hideLoading()
			if (res.result) {
				mapi.msg('修改默认地址成功！')
				getAddressListData()
			} else {
				mapi.msg(res.shortMessage || '修改默认地址失败！')
			}
		} catch (e) {
			hideLoading()
			uni.showToast({
				mask: true,
				title: '修改默认地址失败！',
				icon: 'none'
			});
			console.log('修改默认地址失败！', e);
			console.error(e)
		}
	}
</script>

<style lang="scss">
	.cenScr {
		width: 100%;
		height: calc(100vh - 140rpx);
	}

	.listHover {
		border: 1px solid #53A87F;
	}

	.srcItem {
		width: 100%;
		min-height: 230rpx;
		border-radius: 20rpx;
		background: #fff;
		box-shadow: 0px 10rpx 20rpx rgba(0, 64, 128, 0.04);
		&.gry{
			color: #CFCFCF;
			.ovbx{
				color: #CFCFCF!important;
			}
		}
	}

	.botSec {
		width: 100%;
		min-height: 150rpx;
		background: #fff;
		position: fixed;
		left: 0;
		bottom: 0;
		box-shadow: 0px 10rpx 20rpx rgba(0, 64, 128, 0.2);
	}

	.lbyuan {
		width: 76rpx;
		height: 44rpx;
		border-radius: 44rpx;
		line-height: 45rpx;

		// border: 4rpx solid #fff;
		// box-shadow: 0px 6rpx 10rpx rgba(0, 0, 0, 0.1);
		&.ji {
			color: #fff;
			background: rgba(44, 172, 88, 0.28);
		}

		&.gs {
			color: #fff;
			background: rgba(44, 126, 172, 0.28);
		}
	}

	.itm_btn {
		width: 50rpx;
		min-height: 50rpx;
	}

	.textact {
		color: $base-color;
	}

	.actions {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding-top: 10rpx;
	}

	.defSwitch {
		width: 70rpx;
		height: 36rpx;
		border-radius: 24rpx;
		margin-right: 20rpx;
		position: relative;

		.acSwitch {
			width: 28rpx;
			height: 28rpx;
			border-radius: 50%;
			position: absolute;
			top: 5rpx;
			right: 8rpx;
			background-color: #58AB83;
		}

		.unact {
			width: 28rpx;
			height: 28rpx;
			border-radius: 50%;
			position: absolute;
			top: 5rpx;
			left: 8rpx;
			background-color: rgba(153, 153, 153, 0.70);
		}
	}

	.swi_text {
		color: #666;
		text-align: center;
		font-family: ABeeZee;
		font-size: 28rpx;
		font-weight: 400;
		letter-spacing: 0.28px;
		margin-right: 20rpx;
	}
</style>